#!/bin/sh
#
# SIPproxy64 script for init.d
#
# Available commands: start, stop, restart, reload.
#


ETCDIR=`dirname "$0"`/../sipproxy64

[ -r "$ETCDIR/config" ] || exit
. "$ETCDIR/config"

if [ -z "$V4LISTEN" -o -z "$V6LISTEN" ]
then
	echo >&2 Please setup at least V4LISTEN and V6LISTEN in $0
	exit 1
fi

if [ -z "$V4INTERFACE" -o -z "$V6INTERFACE" ]
then
	echo >&2 Please setup at least V4INTERFACE and V6INTERFACE in $0
	exit 1
fi

V4PHONES=''
for V4ONLY in $( cat "$ETCDIR/v4only" | sed -e 's/[ \t]*//' -e 's/^#.*//' -e '/^$/d' )
do
	V4PHONES="$V4PHONES $V4ONLY"
done

V6PHONES=''
for V6ONLY in $( cat "$ETCDIR/v6only" | sed -e 's/[ \t]*//' -e 's/^#.*//' -e '/^$/d' )
do
	V6PHONES="$V6PHONES $V6ONLY"
done

setup() {
	for P in $V4PHONES
	do
		IP6=`echo $P | sed 's/.*=//'`
		ip -6 addr add "$IP6/128" dev "$V6INTERFACE"
	done
	for P in $V6PHONES
	do
		IP4=`echo $P | sed 's/=.*//'`
		ip -4 addr add "$IP4/24" dev "$V4INTERFACE"
	done
	sleep 10
}


teardown () {
	for P in $V4PHONES
	do
		IP6=`echo $P | sed 's/.*=//'`
		ip -6 addr del "$IP6/128" dev "$V6INTERFACE"
	done
	for P in $V6PHONES
	do
		IP4=`echo $P | sed 's/=.*//'`
		ip -4 addr del "$IP4/24" dev "$V4INTERFACE"
	done
}

start() {
	V4UPOPT=
	V6UPOPT=
	[ -n "$V4UPLINK" ] && V4UPOPT="-u"
	[ -n "$V6UPLINK" ] && V6UPOPT="-U"
	setsid /tmp/sipproxy64/sipproxy64 -l "$V4LISTEN" -L "$V6LISTEN" $V4UPOPT $V4UPLINK $V6UPOPT $V6UPLINK $V4PHONES $V6PHONES > /tmp/sipproxy64.log
}

stop() {
	killall /tmp/sipproxy64/sipproxy64
}


case "$1" in

start)
	setup
	start
	;;

stop)
	stop
	teardown
	;;

restart)
	stop
	teardown
	sleep 4
	setup
	start
	;;

reload)
	killall -HUP sipproxy64
	sleep 1
	start
	;;

*)
	echo "Usage: $0 start|stop|restart"
	;;

esac
